package com.baizhi.service;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.alibaba.fastjson.JSON;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectRequest;
import com.baizhi.dao.UserDao;
import com.baizhi.entity.User;
import com.baizhi.util.AliYun;
import com.baizhi.vo.MonthAndCount;
import io.goeasy.GoEasy;
import io.goeasy.publish.GoEasyError;
import io.goeasy.publish.PublishListener;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;

@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public Map<String, Object> queryByPage(int page, int size) {
        Map<String,Object> map = new HashMap<>();
        //总页数
//        map.put("");
        //当前是第几页

        //page-1*size
        List<User> list = userDao.queryRange((page - 1) * size, size);
        //分页查的数据
        map.put("data",list);

        //存储当前数据
        map.put("page",page);

        //存储总页数    总条数 / 每页显示的条数  = 页数
        int countNum = userDao.queryPageNum();  //总条数
        //总页数
        int pageNum = countNum%size == 0?countNum/size:countNum/size+1;
        map.put("pageNum",pageNum);
        return map; // 当前页数据 总数据
    }



    @Override
    public void updateStatus(String id, int status) {
        userDao.updateStatus(id,status);
    }

    @Override
    public void delete(String id) {
        // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1（杭州）为例，Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
        String endpoint = "https://oss-cn-beijing.aliyuncs.com";
// 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = "LTAI5tFSKfBwJ7yXUCf2KY8g";
        String accessKeySecret = "t0qbCLwoX1OvHZwp79Y0kqEobldtJ2";
// 填写Bucket名称，例如examplebucket。
        String bucketName = "2017class";
// 填写文件名。文件名包含路径，不包含Bucket名称。例如exampledir/exampleobject.txt。

        User user = userDao.queryOne(id);
        String[] ss = user.getHeadimg().split("http://2017class.oss-cn-beijing.aliyuncs.com/");



        String objectName = ss[1];

        OSS ossClient = null;
        try {
            // 创建OSSClient实例。
            ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

            // 删除文件。
            ossClient.deleteObject(bucketName, objectName);
        } catch (OSSException e){
            e.printStackTrace();
        } finally {
            // 关闭OSSClient。
            ossClient.shutdown();
        }
        userDao.delete(id);
        queryMonthAndCount2();
    }

    @Override
    public void add(MultipartFile file,User user) {
        //头像的上传


        //得到上传时文件的名字
        String fileName = file.getOriginalFilename();
        Date date = new Date();
        long time = date.getTime();
        String finalName = time+fileName;
        AliYun.uploadByBytes(file,finalName);

    //user对象中的数据入库
        user.setId(UUID.randomUUID().toString());
        user.setCreatedate(new Date());
        //http://2017class.oss-cn-beijing.aliyuncs.com/11.jpg
        //http://2017class.oss-cn-beijing.aliyuncs.com/2025423.jpg
        user.setHeadimg("http://2017class.oss-cn-beijing.aliyuncs.com/"+finalName);
        user.setStatus(1);

        userDao.add(user);
        queryMonthAndCount2();

    }
    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public void export(int page, int size) {
        List<User> list = userDao.queryRange((page-1)*size, size);
        for (User user : list) {
            String headimg = user.getHeadimg();
            //获取每个user用户的头像名
            String substring = headimg.substring(headimg.lastIndexOf("/") + 1);
            System.out.println(substring);
            AliYun.dowload(substring,"D:\\localpath\\"+substring);
            user.setHeadimg("D:\\localpath\\"+substring);
        }
        //参数：标题，表名，实体类类对象，导出的集合
        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams("应学用户","用户管理"),User.class, list);
        try {
            workbook.write(new FileOutputStream(new File("D://"+new Date().getTime()+"user.xls")));
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                workbook.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public Map<String, Object> queryMonthAndCount() {
        //定义月份数据
        Map<String,Object> map = new HashMap<>();
        List<String> months = Arrays.asList("1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月");
        //男生人数
        List<MonthAndCount> man = userDao.queryByMonthCount("男");
        for (MonthAndCount monthAndCount : man) {
            System.out.println("++++++++"+monthAndCount.getMonth());
            System.out.println("++++++++"+monthAndCount.getCount());
        }
        //女生人数
        List<MonthAndCount> woman = userDao.queryByMonthCount("女");

        //男生每个月份对应的人数
        List<Integer> manCount = new ArrayList<>();
        List<Integer> womanCount = new ArrayList<>();
        //i = 0

        //循环12次 每一次代表一个月份 第一次i=1 代表1月
        for (int i = 1; i <= 12; i++) {
            boolean flag = false;
            for (MonthAndCount monthAndCount : man) {
                if(monthAndCount.getMonth().equals(i+"")){
                    manCount.add(monthAndCount.getCount());
                    flag = true;
                }
            }
            if(flag == false){
                manCount.add(0);
            }

            boolean flag2 = false;
            for (MonthAndCount monthAndCount : woman) {
                if(monthAndCount.getMonth().equals(i+"")){
                    womanCount.add(monthAndCount.getCount());
                    flag2 = true;
                }
            }
            if(flag2 == false){
                womanCount.add(0);
            }
        }

        map.put("months",months);
        map.put("manCount",manCount);
        map.put("womanCount",womanCount);
        return map;
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public void queryMonthAndCount2() {
        Map<String, Object> map = queryMonthAndCount();
        String json = JSON.toJSONString(map);
        GoEasy goEasy = new GoEasy( "http://rest-hangzhou.goeasy.io", "BC-eb6bddf9c4d24e24840e340a3bbbd34d");
        goEasy.publish("yx_channel", json,new PublishListener(){
            @Override
            public void onSuccess() {
                System.out.println("发送成功");
            }

            @Override
            public void onFailed(GoEasyError error) {
                System.out.println("失败状态码"+error.getCode()+",失败原因"+error.getContent());
            }
        });
    }
}
